package de.schillermann.glowstonemysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Mario Schillermann
 */
final public class MysqlApi {
    
    private Connection connection = null;

    private final String url;
    private final String database;
    private final String user;
    private final String password;
    
    public MysqlApi(String url, String database, String user, String password)
    {
        this.url       = url;
        this.database  = database;
        this.user     = user;
        this.password = password;
    }
    
    public String getUrl()
    {
        return this.url;
    }
    
    public String getDatabase()
    {
        return this.database;
    }
    
    public Connection getConnection()
    {
        if(this.connection == null)
        {
            try
            {
                Class.forName("com.mysql.jdbc.Driver");
            }
            catch(ClassNotFoundException ex)
            {
                System.err.print("MySQL-Driver not found! Error: " + ex.getMessage());
                return null;
            }

            try
            {
                this.connection = DriverManager.getConnection(
                    this.getUrl() + this.getDatabase(),
                    this.user,
                    this.password
                );
                
                System.out.print("Connected to Database " + this.getDatabase());
            }
            catch(SQLException ex)
            {
                System.err.print(
                    "Can not connect to MySQL! SQL: " + ex.getSQLState() +
                    " Error: " + ex.getMessage()
                );
            }
        }
        return this.connection;
    }
}
